 <?php
 header('Content-type: application/json');
include 'Node.php';
/*
 * http://www.phpro.org/tutorials/Introduction-to-PHP-PDO.html
 * http://php.net/explode
 * http://www.php.net/manual/en/pdostatement.fetch.php
 * */



$dbh = new PDO("mysql:host=localhost;dbname=tree4sites", 'root', '');

function addNodeChlids($node,$dbh){
	
	$sth = $dbh->prepare('SELECT * FROM `site` WHERE id = '.$node->id);
	$sth->execute();
	$row = $sth->fetch();	
	if($row !== false) {
		/* get the current node chlildens*/
		$listOfChildren = $row['children'];
		//print_r($listOfChildren);
		if($listOfChildren != ""){
		$listOfChildrenArray = explode(",", $listOfChildren);
			foreach ($listOfChildrenArray as $childId){
				$sth = $dbh->prepare('SELECT * FROM `site` WHERE id = '.$childId);
				$sth->execute();
				$childRow = $sth->fetch();
					
				/*Create a new child node*/
				$childNode = new Node();
				$childNode->id = $childRow['id'];
				$childNode->name = $childRow['name'];	
				addNodeChlids($childNode,$dbh);
				array_push($node->children, $childNode);
			}
		}
	}else{
		$node = "NULL";
	}
}


/* main */
$id = 1;
if(isset($_GET["id"])){
	$id = $_GET["id"];
}

$sth = $dbh->prepare('SELECT * FROM `site` WHERE id = '.$id);
$sth->execute();
$row = $sth->fetch();
if($row !== false) {

	$masterNode = new Node();
	$masterNode->name = $row['name'];;
	$masterNode->id = $id;
	
	addNodeChlids($masterNode,$dbh);
	echo json_encode($masterNode);
	
}else {
	echo "NODE NOT EXIST";
}


?>

